<template>
	<div class="order-detail-container">
		<!--商品列表-->
		<van-card v-for="item in order.detailList" :key="item.id" :num="item.count" :price="item.price.toFixed(2)"
			:title="item.product_name" :desc="item.product_spec" :thumb="item.product_pic" />
		<!-- 订单备注 -->
		<van-cell title="订单备注" :value="order.remark" label="" />
		<!-- 配送信息 -->
		<van-cell title="配送服务" label="快递运输,工作日、双休日与节假日均可送货" />
		<!-- 收货地址 -->
		<van-cell title="收货地址">
			<template #label>
				<div>{{ order.receiver }} {{ order.phone }}</div>
				<div>{{ order.address}}</div>
			</template>
		</van-cell>
		<!--费用信息-->
		<van-cell title="商品金额" :value="`¥${orderAmount}`" />
		<van-cell title="运费" :value="`¥0.00`" />
		<van-cell title="总价" :value="`¥${orderAmount}`" />
		<!-- 去支付按钮 -->
		<div v-if="order.id && order.status==0">
			<van-button type="primary" size="large" @click="onClickPay">去支付</van-button>
		</div>
		<!-- 删除按钮 -->
		<div v-if="order.id">
			<van-button type="danger" size="large" @click="onClickDelete">删除订单</van-button>
		</div>
	</div>
</template>

<script>
	import { showToast, showConfirmDialog } from 'vant';
	import { getOrderDetailByIdAPI, deleteOrderByIdAPI } from "@/api/order.js";
	import { getAddressDetailByIdAPI } from "@/api/address.js";
	export default {
		data() {
			// 从路由参数获取订单ID，确保是有效的数字
			const routeId = this.$route.query.id;
			let orderId = 0;
			if (routeId) {
				const parsedId = parseInt(routeId);
				if (!isNaN(parsedId) && parsedId > 0) {
					orderId = parsedId;
				}
			}
			
			return {
				id: orderId,
				order: { detailList: [] },
				APIDomainName: import.meta.env.VITE_APIDomainName || '/', // 接口域名
			};
		},

		// 计算属性
		computed: {
			//计算一个订单的总金额
			orderAmount() {
				let amount = 0;
				this.order.detailList.forEach(item => {
					amount += item.count * item.price;
				});
				return amount.toFixed(2);
			},
		},
		//生命周期钩子函数
		created() {
			// 只有在有有效ID时才获取订单详情
			if (this.id > 0) {
				this.getOrderDetail();
			} else {
				showToast("订单ID无效");
				setTimeout(() => {
					this.$router.back();
				}, 1500);
			}
		},
		methods: {
			// 获取订单详情
			getOrderDetail() {
				if (!this.id) {
					showToast("订单ID无效");
					this.$router.back();
					return;
				}
				getOrderDetailByIdAPI(this.id).then(result => {
					// 后端返回 R<OrderDetailVo>，result.data 是 OrderDetailVo 对象
					if (result.data) {
						// 映射数据字段，确保与前端期望的格式一致
						const orderData = result.data;
						
						// 处理订单明细列表
						let detailList = [];
						if (orderData.orderItemList) {
							// 后端返回的字段名（最优先）
							detailList = Array.isArray(orderData.orderItemList) ? orderData.orderItemList : [];
						} else if (orderData.detailList) {
							detailList = Array.isArray(orderData.detailList) ? orderData.detailList : [];
						} else if (orderData.detail_list) {
							detailList = Array.isArray(orderData.detail_list) ? orderData.detail_list : [];
						} else if (orderData.items) {
							detailList = Array.isArray(orderData.items) ? orderData.items : [];
						} else if (orderData.orderDetails) {
							detailList = Array.isArray(orderData.orderDetails) ? orderData.orderDetails : [];
						} else if (orderData.orderDetailList) {
							detailList = Array.isArray(orderData.orderDetailList) ? orderData.orderDetailList : [];
						} else if (orderData.order_item_list) {
							detailList = Array.isArray(orderData.order_item_list) ? orderData.order_item_list : [];
						} else if (orderData.goodsList) {
							detailList = Array.isArray(orderData.goodsList) ? orderData.goodsList : [];
						} else if (orderData.goods_list) {
							detailList = Array.isArray(orderData.goods_list) ? orderData.goods_list : [];
						}
						
						// 映射订单明细字段（根据订单明细表结构）
						detailList = detailList.map(item => ({
							id: item.id || item.orderDetailId || item.order_detail_id,
							order_id: item.order_id || item.orderId,
							product_id: item.product_id || item.productId,
							product_name: item.product_name || item.productName || item.name || '',
							product_spec: item.product_spec || item.productSpec || item.spec || '',
							product_pic: item.product_pic || item.productPic || item.pic || '',
							price: parseFloat(item.price || 0),
							count: parseInt(item.count || 0)
						}));
						
						// 处理收货地址信息（尝试多种字段名组合）
						const addressId = orderData.address_id || orderData.addressId;
						
						// 尝试从订单数据中直接获取地址信息
						let receiver = orderData.receiver || orderData.receiverName || orderData.name || 
						              orderData.receiver_name || '';
						let phone = orderData.phone || orderData.receiverPhone || orderData.tel || 
						           orderData.receiver_phone || orderData.receiverTel || '';
						
						// 尝试获取完整地址或拼接地址
						let address = orderData.address || orderData.receiverAddress || 
						             orderData.fullAddress || orderData.full_address || '';
						
						// 如果没有完整地址，尝试拼接省市区和详细地址
						if (!address) {
							const province = orderData.province || '';
							const city = orderData.city || '';
							const county = orderData.county || orderData.district || '';
							const addressDetail = orderData.addressDetail || orderData.address_detail || '';
							address = province + city + county + addressDetail;
						}
						
						// 如果地址信息不完整，且有 address_id，则通过 address_id 查询地址详情
						if (addressId && (!receiver || !phone || !address)) {
							this.loadAddressById(addressId).then(addressInfo => {
								if (addressInfo) {
									this.order.receiver = addressInfo.name || receiver;
									this.order.phone = addressInfo.tel || phone;
									// 拼接完整地址
									const fullAddress = (addressInfo.province || '') + 
									                   (addressInfo.city || '') + 
									                   (addressInfo.county || '') + 
									                   (addressInfo.addressDetail || addressInfo.address_detail || '');
									this.order.address = fullAddress || address;
								}
							}).catch(() => {
								// 如果查询地址失败，使用已获取的信息
								console.warn("通过 address_id 查询地址详情失败");
							});
						}
						
						this.order = {
							// 订单主表字段（book_order）
							id: orderData.id || orderData.orderId,
							order_no: orderData.order_no || orderData.orderNo || '',
							user_id: orderData.user_id || orderData.userId,
							address_id: addressId,
							amount: parseFloat(orderData.amount || 0),
							remark: orderData.remark || '',
							status: orderData.status !== undefined ? parseInt(orderData.status) : -1,
							created_at: orderData.created_at || orderData.createdAt || '',
							updated_at: orderData.updated_at || orderData.updatedAt || '',
							// 收货地址信息（可能从地址表关联查询得到）
							receiver: receiver,
							phone: phone,
							address: address,
							// 订单明细列表（从订单明细表关联查询得到）
							detailList: detailList
						};
					} else {
						showToast("订单不存在");
						setTimeout(() => {
							this.$router.back();
						}, 1500);
					}
				}).catch((error) => {
					console.error("获取订单详情失败:", error);
					const errorMsg = error?.response?.data?.msg || error?.message || "获取订单详情失败";
					showToast(errorMsg);
					setTimeout(() => {
						this.$router.back();
					}, 1500);
				});
			},
			//触发支付
			onClickPay() {
				showToast('支付功能还未实现');
			},

			//触发删除订单
			onClickDelete() {
				showConfirmDialog({
					message: '确定要删除这个订单吗？'
				}).then(() => {
					deleteOrderByIdAPI(this.id).then(() => {
						showToast("订单已删除");
						setTimeout(() => {
							this.$router.back();
						}, 1000);
					}).catch((error) => {
						console.error("删除订单失败:", error);
						showToast("删除订单失败");
					});
				}).catch(() => {
					// 用户取消操作
				});
			},
			
			// 通过地址ID加载地址详情
			loadAddressById(addressId) {
				if (!addressId) {
					return Promise.resolve(null);
				}
				return getAddressDetailByIdAPI(addressId).then(result => {
					if (result.data) {
						return {
							name: result.data.name || '',
							tel: result.data.tel || '',
							province: result.data.province || '',
							city: result.data.city || '',
							county: result.data.county || '',
							addressDetail: result.data.addressDetail || result.data.address_detail || ''
						};
					}
					return null;
				}).catch(() => {
					return null;
				});
			},

		},
	};
</script>

<style lang="less" scoped>
	// 定义主题色变量（与其他页面保持一致）
	@mainColor: #8b4513; // 棕色主题色
	@bgColor: #f9f5ed; // 米黄色背景
	@lightBrown: #f5e8d0; // 浅棕色
	@darkBrown: #5a4a42; // 深棕色

	.order-detail-container {
		background: @bgColor;
		min-height: 100vh;
		padding-top: 46px;
		padding-bottom: 20px;
	}

	// 商品卡片样式
	/deep/ .van-card {
		margin: 10px;
		width: calc(100% - 20px);
		box-sizing: border-box;
		border-radius: 8px;
		background-color: white;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
		border: 1px solid #f0e8d9;
		border-left: 4px solid @mainColor; // 左侧主题色标识线

		.van-card__content {
			justify-content: space-evenly;
		}

		.van-card__title {
			font-size: 15px;
			color: @darkBrown;
			font-weight: 500;
		}

		.van-card__desc {
			color: #666;
			font-size: 13px;
		}

		.van-card__price {
			color: #e53935;
			font-weight: bold;
			font-size: 16px;
		}

		.van-card__num {
			font-size: 14px;
			color: #666;
		}
	}

	// 单元格样式
	/deep/ .van-cell {
		background-color: white;
		margin: 10px;
		width: calc(100% - 20px);
		box-sizing: border-box;
		border-radius: 8px;
		box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
		border-left: 4px solid @mainColor; // 左侧主题色标识线

		.van-cell__title {
			color: @darkBrown;
			font-weight: 500;
		}

		.van-cell__value {
			color: @darkBrown;
			font-weight: 500;
			
			// 总价特殊样式
			&:last-child {
				color: #e53935;
				font-weight: bold;
				font-size: 16px;
			}
		}

		.van-cell__label {
			color: #666;
			font-size: 14px;
			line-height: 1.6;
		}
	}

	// 按钮样式
	/deep/ .van-button {
		margin: 10px;
		width: calc(100% - 20px);
		box-sizing: border-box;
		border-radius: 8px;
		font-size: 16px;
		height: 48px;
	}

	/deep/ .van-button--primary {
		background-color: @mainColor;
		border-color: @mainColor;
		color: white;

		&:active {
			background-color: darken(@mainColor, 10%);
			border-color: darken(@mainColor, 10%);
		}
	}

	/deep/ .van-button--danger {
		background-color: #ee0a24;
		border-color: #ee0a24;

		&:active {
			background-color: darken(#ee0a24, 10%);
			border-color: darken(#ee0a24, 10%);
		}
	}
</style>